<!--
 * @Description: 活动 - 疯狂星期五添加商品
 * @Author: liyujie
 * @Date: 2021/05/28
 * @Last Modified by: liyujie
 * @Last Modified time: 2021/05/28
-->
<template>
    <div class="wrapper crazy-friend-goods-add">
        <div class="content-wrapper">
            <!-- header -->
            <div class="header">
                <div class="header-title">
                    疯狂星期五
                </div>
                <div class="header-content">
                    <el-button
                        type="primary"
                        size="medium"
                        style="width: 104px"
                        @click="$refs.goodsSelect.show(2, requestUrl)"
                    >
                        {{ this.ruleForm.tableData.length ? '继续添加' : '选择商品' }}
                    </el-button>
                    <el-button
                        type="primary"
                        size="medium"
                        style="width: 104px;margin-left: 32px"
                        @click="goodsImportDialog = true"
                    >
                        导入商品
                    </el-button>
                </div>
            </div>
            <!-- /header -->

            <el-form
                :model="ruleForm"
                :rules="rules"
                ref="ruleForm"
                v-if="ruleForm.tableData.length"
            >
                <div class="goods-wrapper">
                    <div
                        v-for="(goods, index) in ruleForm.tableData"
                        :key="index"
                        class="goods-item"
                    >
                        <div class="goods-item__header">
                            活动报名商品{{ index + 1 }}
                        </div>
                        <div class="goods-item__content">
                            <div
                                class="select-btn"
                                @click="showGoodsDialog(index)"
                            >
                                重新选择商品
                            </div>
                            <el-button
                                size="medium"
                                style="width: 68px;margin-left: 24px"
                                @click="deleteGoods(index)"
                            >
                                删除
                            </el-button>
                            <div class="goods-info-table">
                                <el-table
                                    :data="goods.baseInfo"
                                    style="width: 100%;"
                                    class="data-table"
                                    :row-style="{height: '130px'}"
                                >
                                    <el-table-column
                                        label="商品信息"
                                        :formatter="emptyFormatter"
                                        width="300"
                                    >
                                        <template slot-scope="scope">
                                            <div class="goods-info">
                                                <img
                                                    :src="scope.row.goods_cover"
                                                    class="goods-cover"
                                                    @click="fnShowPreview(scope.row.goods_cover)"
                                                >
                                                <div class="goods-title">
                                                    {{ scope.row.goods_title }}
                                                </div>
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        label="商品编号"
                                        prop="goods_no"
                                        show-overflow-tooltip
                                        :formatter="emptyFormatter"
                                    />
                                    <el-table-column
                                        prop="type_name"
                                        label="类目"
                                        show-overflow-tooltip
                                        align="center"
                                        :formatter="emptyFormatter"
                                    />
                                    <el-table-column
                                        prop="goods_stock"
                                        label="商品库存"
                                        show-overflow-tooltip
                                        align="center"
                                        :formatter="emptyFormatter"
                                    />
                                    <el-table-column
                                        label="限购数量"
                                        show-overflow-tooltip
                                        align="center"
                                        :formatter="emptyFormatter"
                                    >
                                        <template slot-scope="scope">
                                            {{ scope.row.buy_limit_count === -1 ? '不限' : scope.row.buy_limit_count }}
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        label="佣金"
                                        show-overflow-tooltip
                                        align="center"
                                        :formatter="emptyFormatter"
                                    >
                                        <template slot-scope="scope">
                                            {{ scope.row.goods_commission_rate }}%
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        prop="goods_price"
                                        label="商品单价"
                                        show-overflow-tooltip
                                        align="center"
                                        :formatter="emptyFormatter"
                                    />
                                    <el-table-column
                                        label="其他优惠"
                                        show-overflow-tooltip
                                        align="center"
                                        :formatter="emptyFormatter"
                                    >
                                        <template slot-scope="scope">
                                            <el-popover
                                                placement="top"
                                                width="240"
                                                trigger="click"
                                                v-if="scope.row.benefit_list.length"
                                            >
                                                <div
                                                    v-for="(tag, tagIndex) in scope.row.benefit_list"
                                                    :key="tagIndex"
                                                    style="text-align: center"
                                                >{{ tag.info }}</div>
                                                <el-button
                                                    slot="reference"
                                                    type="text"
                                                >
                                                    查看
                                                </el-button>
                                            </el-popover>
                                            <div v-else>--</div>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                            <div class="product-info-table">
                                <el-table
                                    :data="goods.product_list"
                                    style="width: 100%;"
                                    class="data-table product"
                                    :span-method="objectSpanMethod"
                                    @selection-change="handleSelectAll($event, index)"
                                >
                                    <el-table-column
                                        type="selection"
                                        align="center"
                                        width="48"
                                    >
                                        <template slot-scope="scope">
                                            <el-checkbox
                                                v-model="scope.row.check_status"
                                                :true-label="1"
                                                :false-label="0"
                                                style="margin-bottom: 12px"
                                            />
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        label="商品规格"
                                        show-overflow-tooltip
                                        :formatter="emptyFormatter"
                                        width="200"
                                    >
                                        <template slot-scope="scope">
                                            <div style="margin-bottom: 12px">
                                                {{ scope.row.spec_list | filterSpec }}
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        prop="product_price"
                                        label="学生价"
                                        show-overflow-tooltip
                                        align="center"
                                        :formatter="emptyFormatter"
                                    >
                                        <template slot-scope="scope">
                                            <div style="margin-bottom: 12px">
                                                {{ scope.row.product_price }}
                                            </div>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        label="活动价"
                                        :formatter="emptyFormatter"
                                    >
                                        <template slot-scope="scope">
                                            <el-form-item
                                                :prop="`tableData[${index}].product_list[${scope.$index}]`"
                                                :rules="rules.price"
                                            >
                                                <el-input
                                                    v-model="scope.row.price"
                                                    size="small"
                                                    style="width: 162px;"
                                                    :disabled="scope.row.check_status === 0"
                                                    @click.native="clickDisableInput(scope.row)"
                                                />
                                            </el-form-item>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        label="佣金比例"
                                        align="left"
                                        width="500"
                                        :formatter="emptyFormatter"
                                    >
                                        <template slot-scope="scope">
                                            <el-form-item
                                                :prop="`tableData[${index}].commission_rate`"
                                                :rules="rules.commission_rate"
                                                class="el-form-item-commission-rate"
                                            >
                                                <el-input
                                                    v-model="goods.commission_rate"
                                                    size="small"
                                                    style="width: 162px;"
                                                >
                                                    <span
                                                        slot="suffix"
                                                        style="margin-right: 5px"
                                                    >%</span>
                                                </el-input>
                                                <span class="tips">该佣金比例只适用于疯狂星期五活动订单</span>
                                            </el-form-item>
                                        </template>
                                    </el-table-column>
                                    <el-table-column
                                        prop="product_stock"
                                        label="实际库存"
                                        show-overflow-tooltip
                                        align="center"
                                    >
                                        <template slot-scope="scope">
                                            <div style="margin-bottom: 12px">
                                                {{ scope.row.product_stock }}
                                            </div>
                                        </template>
                                    </el-table-column>
                                </el-table>
                            </div>
                        </div>
                    </div>
                </div>
            </el-form>
            <div
                class="empty-view"
                v-else
            >
                <div class="empty-img">
                    <img
                        src="@/assets/image/empty-goods.png"
                        alt=""
                    >
                </div>
                <div class="empty-text">暂未添加商品，点击左上角按钮进行添加商品</div>
            </div>
            <div class="submit-view">
                <el-button
                    type="primary"
                    size="medium"
                    style="width: 120px"
                    :loading="loading"
                    :disabled="!ruleForm.tableData.length"
                    @click="handleSubmit"
                >
                    提交报名
                </el-button>
            </div>
        </div>
        <!--商品选择弹窗-->
        <goods-select
            ref="goodsSelect"
            @change="handleSelectGoods($event, setIndex)"
        />
        <!-- 导入商品 -->
        <goods-import
            :visible.sync="goodsImportDialog"
            :request-url="requestUrl"
            @change="handleSelectGoods($event.list)"
        />
        <!-- 图片预览 -->
        <img-preview
            ref="preview"
        />
    </div>
</template>

<script>
import { back } from '@/mixin/back';
import { deepClone } from "@/assets/js/utils";
import ImgPreview from "@/components/common/img-preview";
import GoodsSelect from "@/components/goods/goods-select-old";
import GoodsImport from "@/components/goods/goods-import";
const numberReg = /(?:^[1-9]([0-9]+)?(?:\.[0-9]{1,2})?$)|(?:^(?:0)$)|(?:^[0-9]\.[0-9](?:[0-9])?$)/;

export default {
    name: 'CrazyFridayGoodsAdd',
    mixins: [back],
    components: {GoodsImport, GoodsSelect, ImgPreview},
    data() {
        const validatePrice = (rule, value, callback) => {
            if(value.check_status && !value.price) {
                callback(new Error('请填写活动价'));
            } else if(value.price && !numberReg.test(value.price)) {
                callback(new Error('活动价必须未数字'));
            } else {
                callback();
            }
        };

        return {
            requestUrl: '/student/shop_goods_activity_friday_sale%5Cget_depot_goods_list',
            ruleForm: {
                tableData: []
            },
            rules: {
                price: [
                    { validator: validatePrice, trigger: 'blur'},
                ],
                commission_rate: [
                    { required: true, message: '请输入佣金', trigger: 'blur' },
                    { pattern: numberReg, message: '佣金须为数字', trigger: 'blur' }
                ]
            },
            // 重新选择商品的index
            setIndex: 0,
            goodsImportDialog: false,
            loading: false
        };
    },
    computed: {},
    watch: {},
    filters: {
        filterSpec (val) {
            if(!val) return '';
            let str = '';

            val.forEach(el => {
                str += el.spec_name + ':' + el.spec_value + '；';
            });
            return str;
        }
    },
    mounted() {
        this.init();
    },

    methods: {
        /**
         * 初始化
         */
        init() {
            this.$store.commit('SET_HEADER', [{title: "APP后台"}, {title: '商城'}, {title: '活动管理'}, {title: '疯狂星期五', path: '/student/crazy-friday-goods-verify'}, {title: '添加商品'}]);
            this.authResult = this.$route.meta.authResult;
        },

        /**
         * 路由跳转
         * @param routeName
         * @param query
         */
        handleRoute(routeName, query) {
            this.$router.push({
                name: routeName,
                query
            });
        },

        /**
         * @description 过滤函数
         */
        emptyFormatter(row, column, val) {
            if (!val) return '--';
            return val;
        },

        /**
         * 预览图片
         * @param   {String}    images      //单图预览
         * @param   {Array}     images      //多图预览
         * @param index
         */
        fnShowPreview(images, index) {
            if (images && Object.prototype.toString.call(images) == '[object String]') {
                this.$refs.preview.show([
                    images
                ]);
            } else if (images && Object.prototype.toString.call(images) == '[object Array]') {
                this.$refs.preview.show(images, index);
            } else {
                this.$message({
                    type: 'warning',
                    message: '图片类型错误'
                });
            }
        },

        /**
         * 显示选择商品弹窗
         * @param index
         */
        showGoodsDialog(index) {
            this.setIndex = index;
            this.$refs.goodsSelect.show();
        },

        /**
         * 选择商品
         * @param data
         * @param index
         */
        handleSelectGoods(data, index) {
            if(Object.prototype.toString.call(data) === '[object Object]') {
                // 更改单个商品
                data.commission_rate = '';
                data.product_list.forEach(item => {
                    item.check_status = 0;
                    item.price = '';
                });
                this.$set(this.ruleForm.tableData, index, deepClone(data));
                this.$set(this.ruleForm.tableData[index], 'baseInfo', [deepClone(data)]);
            } else {
                // 选择商品
                let dataList = deepClone(data).map(item => {
                    item.commission_rate = '';
                    item.product_list.forEach(product => {
                        product.check_status = 0;
                        product.price = '';
                    });
                    return {
                        ...item,
                        baseInfo: [deepClone(item)]
                    };
                });

                this.ruleForm.tableData = [...this.ruleForm.tableData, ...this.checkGoodsRepeat(dataList)];
            }
        },

        /**
         * 过滤重复商品
         */
        checkGoodsRepeat(goodsList) {
            this.ruleForm.tableData.forEach(item => {
                goodsList.forEach((goods, index) => {
                    if(item.goods_no === goods.goods_no) {
                        goodsList.splice(index, 1);
                    }
                });
            });
            return goodsList;
        },

        /**
         * 合并单元格
         * @param row
         * @param column
         * @param rowIndex
         * @param columnIndex
         * @returns {{colspan: number, rowspan: number}}
         */
        objectSpanMethod({ row, column, rowIndex, columnIndex }) {
            if (columnIndex === 4) {
                if(rowIndex === 0) {
                    return {
                        rowspan: 999999,
                        colspan: 1
                    };
                } else {
                    return {
                        rowspan: 0,
                        colspan: 0
                    };
                }
            }
        },

        /**
         * 删除商品
         * @param index
         */
        deleteGoods(index) {
            this.ruleForm.tableData.splice(index, 1);
        },

        /**
         * 点击禁用的input
         * @param row
         */
        clickDisableInput(row) {
            if(!row.check_status) {
                this.$message.warning('请勾选该规格');
            }
        },

        /**
         * 全选
         * @param selection
         * @param index
         */
        handleSelectAll(selection, index) {
            this.ruleForm.tableData[index].product_list.forEach(item => {
                this.$set(item, 'check_status', selection.length ? 1 : 0);
            });
        },

        /**
         * 提交
         */
        handleSubmit() {
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    this.loading = true;
                    let params = deepClone(this.ruleForm.tableData);

                    console.log(params);

                    params.forEach(item => {
                        delete item.baseInfo;
                    });
                    console.log(params);
                    this.$post('/student/shop_goods_activity_friday_sale%5Cadd_goods', {goods_json: JSON.stringify(params)} ,resp=>{
                        if (resp.code === 1) {
                            this.handleRoute('crazyFridayGoodsVerify');
                            this.$notify({
                                title: '提示',
                                type: 'success',
                                message: '保存成功'
                            });
                        } else {
                            this.$notify({
                                title: '提示',
                                type: 'warning',
                                message: resp.msg
                            });
                        }
                        this.loading = false;
                    });
                }
            });
        }
    }
};
</script>

<style lang="less" scoped>
.wrapper {
    width: 100%;
    padding-bottom: 78px;
    .content-wrapper {
        display: flex;
        height: calc(100% - 24px);
        flex-direction: column;
        margin: 12px;
        box-sizing: border-box;
        .submit-view {
            width: 100%;
            height: 68px;
            background: #FFFFFF;
            box-shadow: 0px -1px 4px 0px rgba(0, 0, 0, 0.1);
            position: absolute;
            bottom: 0;
            left: 0;
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1;
            padding-left: 210px;
        }

        /*header*/

        .header {
            height: 141px;
            background: #FFFFFF;
            box-sizing: border-box;
            box-shadow: 0px -1px 0px 0px #F0F2F5;
            display: flex;
            flex-direction: column;
            flex-shrink: 0;

            .header-title {
                border-bottom: 1px solid #EBEEF5;
                font-size: 16px;
                font-family: PingFangSC-Medium, PingFang SC;
                font-weight: 500;
                color: #333333;
                height: 56px;
                position: relative;
                display: flex;
                align-items: center;
                padding: 0 32px;
            }
            .header-content {
                flex: 1;
                padding: 0 32px;
                display: flex;
                align-items: center;
            }
        }

        // 表格
        .data-table {
            ::-webkit-scrollbar {
                width: 6px;
                height: 6px;
            }
            // 操作按钮
            .option-btn-group {
                .el-button {
                    margin-left: 0;
                    margin-right: 10px;
                }
            }
        }

        /*商品列表*/
        .goods-wrapper {
            .select-btn {
                width: 152px;
                height: 36px;
                background: #FFFFFF;
                border-radius: 4px;
                border: 1px solid #1890FF;
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #1890FF;
                display: inline-flex;
                align-items: center;
                justify-content: center;
                cursor: pointer;
                margin-bottom: 20px;
            }
            .goods-item {
                background: #fff;
                margin-top: 12px;
                &:last-child {
                    margin-bottom: 78px;
                }
                &__header {
                    height: 56px;
                    border-bottom: 1px solid #EBEEF5;
                    font-size: 16px;
                    font-family: PingFangSC-Medium, PingFang SC;
                    font-weight: 500;
                    color: #333333;
                    line-height: 16px;
                    padding: 0 32px;
                    display: flex;
                    align-items: center;
                }
                &__content {
                    padding: 20px 32px;
                }
                .goods-info-table {
                    .goods-info {
                        display: flex;
                        align-items: center;
                        .goods-cover {
                            width: 82px;
                            height: 82px;
                            cursor: pointer;
                            margin-right: 12px;
                        }
                        .goods-title {
                            font-size: 14px;
                            display: -webkit-box;
                            -webkit-box-orient: vertical;
                            overflow: hidden;
                            -webkit-line-clamp: 2;
                        }
                    }
                }
                .product-info-table {
                    margin-top: 12px;
                }
            }
            .tips {
                font-size: 12px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #999999;
                margin-left: 10px;
            }
        }

        /*空状态*/
        .empty-view {
            flex: 1;
            background: #fff;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            margin-top: 12px;
            .empty-img {
                width: 256px;
                img {
                    width: 100%;
                }
            }
            .empty-text {
                font-size: 14px;
                font-family: PingFangSC-Regular, PingFang SC;
                font-weight: 400;
                color: #999999;
                line-height: 20px;
                margin-top: 16px;
            }
        }
        /* 分页 */

        .pagination-wrapper {
            padding: 12px 24px;
            .el-pagination {
                float: right;
                padding: 0;
                background-color: transparent;
            }
        }
    }
    /deep/ .el-dialog__header {
        padding-top: 10px;
        box-shadow:0 1px 0 0 rgba(233,233,233,1);
        display: flex;
        align-items: center;
        background: #FAFAFA;
        border-radius: 4px 4px 0 0;
        .el-dialog__title {
            font-weight: 500;
            color: #333;
            font-size: 14px;
        }
        .el-icon-close:before {
            color: rgb(194,194,194);
            font-size: 17px;
            font-weight: bold;
        }
        .el-dialog__headerbtn {
            top: 14px;
        }
    }
    /deep/ .el-textarea__inner {
        resize: none;
    }
    /deep/ .el-form-item__error {
        padding-top: 0;
    }
    /deep/ .el-form-item {
        margin-bottom: 12px;
    }
    /deep/ .el-table.product {
        background: #FBFBFB!important;
        .el-table__body-wrapper {
            padding-top: 12px;
        }
    }
}
</style>
<style lang="less">
.wrapper.crazy-friend-goods-add {
    .el-table {
        th {
            background: #f2f2f2!important;
        }
        td {
            background: #FBFBFB!important;
            border-bottom: 0;
        }
    }
}
</style>
